import json
import math
import re

from args import *
import openai
from flask import request, jsonify
from flask import Flask
from flask_cors import cross_origin
from prompt_type import *


def chat_model(prompt, order, model_uid=model_uid, max_tokens=512, temperature=0.001):
    response = client.chat.completions.create(
        model=f"{model_uid}_{order}",
        messages=[
            {
                "content": prompt,
                "role": "user",
            }
        ],
        max_tokens=max_tokens,
        temperature=temperature
    )

    return response.choices[0].message.content.strip()

#client
client = openai.Client(
    api_key="cannot be empty",
    base_url=f"http://{xinference_url}:{xinference_port}/v1"
)
order_of_model = 1

app = Flask(__name__)
app.debug = False

@app.route('/model/extract/type', methods=['post'])
@cross_origin()
def post_http_entities():
    global order_of_model
    order_of_model = (order_of_model + 1) % num_of_model + 1
    temp_order_of_model = order_of_model

    req = request.get_json()
    context = req.get('content', '')
    limit = min(len(context), limit_len)
    context = context[:limit]
    context = context.strip()
    if not context:
        return {
            "code": 200,
            "data": [],
            "message": "content is empty"
        }
    prompt = get_type_prompt(context)
    response = chat_model(prompt, temp_order_of_model)
    try:
        data = filter_data(response)
    except:
        return {
            "code": 200,
            "data": [],
            "message": "解析json错误"
        }
    ret = {
        "code": 200,
        "data": data,
        "message": "success"
    }
    return jsonify(ret)

def filter_data(data):
    matched_results = {}
    if "其他" in data or "其它" in data:
        return ["其他领域"]
    for i in type_list:
        if i in data:
            return [i]

    return []




if __name__ == '__main__':
    app.run(host='0.0.0.0', port=port)
    #这里指定了地址和端口号。也可以不指定地址填0.0.0.0那么就会使用本机地址ip
